﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using SPMS.Common;
using SPMS.Data;
using SPMS.Web.Models;
using SPMS.Web.Mvc;

namespace SPMS.Web.Controllers
{
    /// <summary>
    /// 生产厂家数据字典
    /// </summary>
    [AuthorizeEx]
    public class ManufactorController : Controller
    {
        #region ---Views

        /// <summary>
        /// 默认视图动作.
        /// </summary>
        /// <returns>视图结果。</returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获得详细视图。
        /// </summary>
        /// <param name="model">查询模型。</param>
        /// <returns>执行结果。</returns>
        public ActionResult DetailView(ManufactorQueryModel model)
        {
            //用于保存实体
            Manufactor entity = null;

            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //查询数据
                entity = context.Manufactors.FirstOrDefault(item => item.Manufactor_ID == model.Manufactor_ID);
            }

            //判断实体是否存在
            if (null == entity)
            {
                //重定向
                return PartialView("_EntityNotFoundPartial");
            }

            //返回视图
            return PartialView(entity);
        }

        #endregion

        #region ---Actions

        /// <summary>
        /// 获得标识图片。
        /// </summary>
        /// <param name="userID">查询模型。</param>
        /// <returns>动作结果。</returns>
        public ActionResult GetLogoImage(ManufactorQueryModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //查询数据
                var entity = context.Manufactors.FirstOrDefault(item => item.Manufactor_ID == model.Manufactor_ID);

                //判断是否有数据
                if (null == entity && entity.Logo != null && entity.Logo.Length > 0)
                {
                    //返回结果
                    return null;
                }

                //返回文件结果
                return this.File(entity.Logo, FileUploadHelper.GetImageMIME(ImageFormat.Png), "Logo.png");
            }
        }

        /// <summary>
        /// 获得账户信息列表。
        /// </summary>
        /// <param name="queryModel">查询模型对象。</param>
        /// <returns>账户信息列表。</returns>
        [HttpGet]
        [JsonHandleError]
        public JsonResult List(JsonPagingQueryModel queryModel)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //用于保存总记录数
                int totalRecord = 0;

                //查询数据
                var query = from item in context.Manufactors.QueryData<Manufactor>(queryModel, out totalRecord).ToArray()
                            select new
                            {
                                item.Manufactor_ID,
                                item.Manufactor_Abbr,
                                item.Manufactor_Name,
                                item.Manufactor_WebSite,
                                item.Memo,
                                HasLogo = (null != item.Logo),
                                LogoUrl = this.GetLogoImageUrl(item)
                            };

                //获得数据
                var data = query.ToArray();

                //返回数据
                return this.JsonEx(true, data, totalRecord);
            }
        }

        /// <summary>
        /// 创建。
        /// </summary>
        /// <param name="model">模型。</param>
        /// <returns>执行结果。</returns>
        [HttpPost]
        [JsonHandleError]
        public ActionResult Create(ManufactorModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //判断同名生产厂家是否已经存在
                if (context.Manufactors.Any(item => item.Manufactor_Name == model.Manufactor_Name))
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的生产厂家已经存在，生产厂家的名称不允许重复。<br/>请将生产厂家的名称指定为其它名称。", model.Manufactor_Name));
                }

                //创建实体
                Manufactor entity = new Manufactor()
                {
                    Manufactor_ID = Guid.NewGuid(),
                    Manufactor_Abbr = model.Manufactor_Abbr,
                    Manufactor_Name = model.Manufactor_Name,
                    Manufactor_WebSite = model.Manufactor_WebSite,
                    Memo = model.Memo
                };


                //判断是否上传了图片
                if (model.Logo_ID.HasValue)
                {
                    //获得签名图片尺寸
                    Size imageSize = this.GetLogoImageSize();

                    //将临时文件转换为图片
                    entity.Logo = FileUploadHelper.ConvertTempFileToImage(context, model.Logo_ID.Value, imageSize.Width, imageSize.Height, 0, System.Drawing.Imaging.ImageFormat.Png, Color.Transparent);
                }

                //添加实体
                context.Manufactors.Add(entity);

                //启动事务
                using (TransactionScope transaction = new TransactionScope())
                {
                    //保存变化
                    context.SaveChanges();

                    //提交事务
                    transaction.Complete();
                }

                //判断是否上传了图片
                if (model.Logo_ID.HasValue)
                {
                    //删除临时文件
                    FileUploadHelper.DeleteTempFile(model.Logo_ID.Value);
                }

                //返回结果
                return this.JsonEx(true, entity.Manufactor_ID);
            }
        }

        /// <summary>
        /// 更新。
        /// </summary>
        /// <param name="model">模型。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        public ActionResult Update(ManufactorModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //判断同名生产厂家是否已经存在
                if (context.Manufactors.Any(item => item.Manufactor_Name == model.Manufactor_Name && item.Manufactor_ID != model.Manufactor_ID))
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的生产厂家已经存在，生产厂家的名称不允许重复。<br/>请将生产厂家的名称指定为其它名称。", model.Manufactor_Name));
                }

                //获得实体
                Manufactor entity = context.Manufactors.FirstOrDefault(item => item.Manufactor_ID == model.Manufactor_ID);

                //判断是否存在
                if (null == entity)
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的生产厂家信息不存在，无法更新。<br/>请确认此生产厂家是否已经被删除。", model.Manufactor_Name));
                }

                //判断指定的账户是否存在
                if (null != entity)
                {
                    //判断是否上传了图片
                    if (model.Logo_ID.HasValue)
                    {
                        //获得签名图片尺寸
                        Size imageSize = this.GetLogoImageSize();

                        //将临时文件转换为图片
                        entity.Logo = FileUploadHelper.ConvertTempFileToImage(context, model.Logo_ID.Value, imageSize.Width, imageSize.Height, 0, System.Drawing.Imaging.ImageFormat.Png, Color.Transparent);
                    }

                    //更新实体
                    entity.Manufactor_Abbr = model.Manufactor_Abbr;
                    entity.Manufactor_Name = model.Manufactor_Name;
                    entity.Manufactor_WebSite = model.Manufactor_WebSite;
                    entity.Memo = model.Memo;

                    //启动事务
                    using (TransactionScope transaction = new TransactionScope())
                    {
                        //保存变化
                        context.SaveChanges();

                        //提交事务
                        transaction.Complete();
                    }

                    //判断是否上传了图片
                    if (model.Logo_ID.HasValue)
                    {
                        //删除临时文件
                        FileUploadHelper.DeleteTempFile(model.Logo_ID.Value);
                    }
                }

                //返回结果
                return this.JsonEx();
            }
        }

        /// <summary>
        /// 获得详细信息。
        /// </summary>
        /// <param name="model">查询模型。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [HttpGet]
        [JsonHandleError]
        public ActionResult Detail(ManufactorQueryModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //查询数据
                var entity = context.Manufactors.FirstOrDefault(item => item.Manufactor_ID == model.Manufactor_ID);

                //判断是否有数据
                if (null == entity)
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的生产厂家信息不存在。<br/>请确认此生产厂家是否已经被删除。", model.Manufactor_Name));
                }

                //创建数据
                var data = new
                {
                    entity.Manufactor_ID,
                    entity.Manufactor_Abbr,
                    entity.Manufactor_Name,
                    entity.Manufactor_WebSite,
                    entity.Memo,
                    HasLogo = (null != entity.Logo && entity.Logo.Length > 0),
                    LogoUrl = this.GetLogoImageUrl(entity)
                };

                //返回数据
                return this.JsonEx(true, data, 1);
            }
        }

        /// <summary>
        /// 删除。
        /// </summary>
        /// <param name="model">模型。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        public ActionResult Delete(ManufactorModel model)
        {
            //判断模型是否有效
            if (null == model)
            {
                //直接返回
                return this.JsonEx();
            }

            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //获得账户信息
                Manufactor entity = context.Manufactors.FirstOrDefault(item => item.Manufactor_ID == model.Manufactor_ID);

                //判断指定的账户是否存在
                if (null != entity)
                {
                    //删除
                    context.Manufactors.Remove(entity);

                    //启动事务
                    using (TransactionScope transaction = new TransactionScope())
                    {
                        //保存变化
                        context.SaveChanges();

                        //提交事务
                        transaction.Complete();
                    }
                }

                //返回结果
                return this.JsonEx();
            }
        }

        #endregion

        #region ---Private Method

        /// <summary>
        /// 获得徽标图片尺寸。
        /// </summary>
        /// <value>
        /// 徽标图片尺寸。
        /// </value>
        private Size GetLogoImageSize()
        {
            return new Size(128, 128);
        }

        /// <summary>
        /// 获得徽标图片地址。
        /// </summary>
        /// <param name="entity">生产厂家实体。</param>
        /// <returns>
        /// 徽标图片地址。
        /// </returns>
        private string GetLogoImageUrl(Manufactor entity)
        {
            //判断是否有徽标
            if (entity.Logo != null && entity.Logo.Length > 0)
            {
                //返回徽标地址
                return string.Format("{0}?Manufactor_ID={1:B}", this.Url.Action("GetLogoImage"), entity.Manufactor_ID);
            }
            else
            {
                //返回默认图片地址
                return this.Url.Content("~/Content/Images/logo_24.png");
            }
        }

        #endregion
    }
}
